package com.example.shopdemo.service;

import com.example.shopdemo.dto.ShopDTO;
import com.example.shopdemo.dto.ShopExecution;
import com.example.shopdemo.entity.Shop;
import com.example.shopdemo.entity.ShopCategory;
import com.example.shopdemo.enums.ShopStateEnum;
import com.example.shopdemo.exception.ShopEditException;
import com.example.shopdemo.repository.ShopCategoryRepository;
import com.example.shopdemo.repository.ShopRepository;
import com.example.shopdemo.utils.FileUtil;
import com.example.shopdemo.utils.ImageUtil;
import com.example.shopdemo.utils.SpecificationsBuilder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;


import java.util.Date;

/**
 * @author ：Anitaxiaofeng
 * @description：
 * @create 2018-01-16
 **/
@Service
@Slf4j
public class ShopServiceImpl {


    @Autowired
    private ShopRepository shopRepository;

    @Autowired
    private ShopCategoryRepository shopCategoryRepository;

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public ShopExecution getShopList(Shop shopCondition, int page, int size){

        String shopId = String.valueOf(shopCondition.getShopId());
        String shopCategoryId = String.valueOf(shopCondition.getShopCategoryId());
        String parentCategoryId = String.valueOf(shopCondition.getParentCategoryId());
        String areaId = String.valueOf(shopCondition.getAreaId());
        String shopName = shopCondition.getShopName();
        String enableStatus = String.valueOf(shopCondition.getEnableStatus());
        Long ownerId = shopCondition.getOwnerId();

        SpecificationsBuilder<Shop> specificationsBuilder = new SpecificationsBuilder<>();
        boolean test= StringUtils.isEmpty(shopId);
        if(!(StringUtils.isEmpty(shopId)|| "null".equals(shopId))){
            specificationsBuilder.with("shopId","=",shopId);
        }
        if(!(StringUtils.isEmpty(shopCategoryId)||"null".equals(shopCategoryId))){
            specificationsBuilder.with("shopCategoryId","=",shopCategoryId);
        }
        if(!(StringUtils.isEmpty(parentCategoryId)||"null".equals(parentCategoryId))){
            specificationsBuilder.with("parentCategoryId","=",parentCategoryId);
        }
        if(!(StringUtils.isEmpty(areaId)||"null".equals(areaId))){
            specificationsBuilder.with("areaId","=",areaId);
        }
        if(!(StringUtils.isEmpty(shopName)||"null".equals(shopName))){
            specificationsBuilder.with("shopName",":",shopName);
        }
        if(!(StringUtils.isEmpty(enableStatus)||"null".equals(enableStatus))){
            specificationsBuilder.with("enableStatus","=",enableStatus);
        }
        if(!(StringUtils.isEmpty(ownerId)||"null".equals(ownerId))){
            specificationsBuilder.with("ownerId","=",ownerId);
        }
        Specification<Shop> spec = specificationsBuilder.build();

        Pageable pageable = new PageRequest(page,size,new Sort(new Sort.Order(Sort.Direction.DESC,"priority")));
        Page<Shop> shopPage = shopRepository.findAll(spec,pageable);
        ShopExecution se = new ShopExecution();
        if(shopPage.getContent()!=null){
            se.setShopList(shopPage.getContent());
            se.setCount(new Long(shopPage.getTotalElements()).intValue());
        }else{
            se.setState(ShopStateEnum.INNER_ERROR.getKey());
        }
        return se;
    }



    public ShopDTO getByShopId(long shopId){

        String querySql = String.format("select s.shop_id,s.shop_name,s.shop_desc,s.shop_addr,s.phone,s.shop_img,s.priority,s.create_time,s.last_edit_time,s.enable_status,s.advice, a.area_id,a.area_name,sc.shop_category_id,sc.shop_category_name " +
                "from shop s,area a,shop_category sc where s.shop_id = '%d' and s.shop_category_id=sc.shop_category_id and s.area_id = a.area_id ",shopId);
        RowMapper<ShopDTO> rowMapper = new BeanPropertyRowMapper<>(ShopDTO.class);
        return jdbcTemplate.queryForObject(querySql,rowMapper);

    }



    @Transactional
    public ShopExecution addShop(Shop shop, MultipartFile shopImg) {
        if (shop == null) {
            return new ShopExecution(ShopStateEnum.NULL_SHOP_INFO);
        }
        try {
            shop.setEnableStatus(0);
            shop.setCreateTime(new Date());
            shop.setLastEditTime(new Date());
            if (shop.getShopCategoryId() != null) {
                ShopCategory sc = shopCategoryRepository.findOne(shop.getShopCategoryId());
                Long parentCategoryId = sc.getParentId();
                shop.setParentCategoryId(parentCategoryId);
            }
            Shop shopResult = shopRepository.save(shop);
            if (shopResult == null) {
                throw new RuntimeException("店铺创建失败");
            } else {
                try {
                    if (shopImg != null) {
                        addShopImg(shop, shopImg);
                        //addShopImg会将图片的地址付给shop的imgurl，所以需要更新shop
                        Shop updateShop = shopRepository.findOne(shop.getShopId());
                        BeanUtils.copyProperties(shop,updateShop);
                        Shop updateShopResult = shopRepository.save(updateShop);
                        if(updateShopResult == null) {
                            throw new RuntimeException("创建图片地址失败");
                        }
                        return new ShopExecution(ShopStateEnum.CHECK, updateShopResult);
                    }
                    return new ShopExecution(ShopStateEnum.CHECK,shopResult);
                } catch (Exception e) {
                    throw new RuntimeException("addShopImg error:" + e.getMessage());
                }
            }
        } catch (Exception e) {
            throw new RuntimeException("insertShop erro:" + e.getMessage());
        }
    }


    public ShopExecution modifyShop(Shop shop,MultipartFile shopImg)throws ShopEditException{
        //1.判断是否需要处理图片
        //2.更新店铺信息
        if(shop == null || shop.getShopId()==null){
            return new ShopExecution(ShopStateEnum.NULL_SHOPID);
        }else{
            try{
                Shop tempShop = shopRepository.findOne(shop.getShopId());
                if(shopImg!=null) {
                    if (tempShop.getShopImg() != null) {
                        FileUtil.deleteFile(tempShop.getShopImg());
                    }
                    addShopImg(tempShop, shopImg);
                }
                    tempShop.setLastEditTime(new Date());
                    tempShop.setAreaId(shop.getAreaId());
                    tempShop.setShopName(shop.getShopName());
                    tempShop.setShopAddr(shop.getShopAddr());
                    tempShop.setPhone(shop.getPhone());
                    tempShop.setShopDesc(shop.getShopDesc());
                    Shop updateResult = shopRepository.save(tempShop);
                    if(updateResult==null){
                        return new ShopExecution(ShopStateEnum.INNER_ERROR);
                    } else {
                        return new ShopExecution(ShopStateEnum.SUCCESS,updateResult);
                    }
            }catch(Exception e){
                throw new ShopEditException("修改商铺信息失败");
            }
        }
    }

    private void addShopImg(Shop shop, MultipartFile shopImg) {
        String shopImagePath = FileUtil.getShopImagePath(shop.getShopId());// /upload/images/item/shop/shopid/
        String shopImgAddr = ImageUtil.generateThumbnail(shopImg,shopImagePath);
        shop.setShopImg(shopImgAddr);
    }

    public Shop getShopByShopId(Long shopId){
        return shopRepository.findOne(shopId);
    }


}






